package com.lianzhihui.romeex.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.lianzhihui.romeex.MyApplication;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.AppStatusManager;
import com.lianzhihui.romeex.config.DataManager;
import com.lianzhihui.romeex.inter.CustomAllCallback;
import com.lianzhihui.romeex.mvp.presenter.SyncUserPresenter;
import com.lianzhihui.romeex.mvp.view.SyncUserView;
import com.lianzhihui.romeex.ui.account.WalletManagerActivity;
import com.lianzhihui.romeex.ui.base.BaseNoRestartActivity;
import com.lianzhihui.romeex.utils.LanguageUtil;
import com.lianzhihui.romeex.utils.MyToast;
import com.lianzhihui.romeex.utils.PreferenceUtils;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.utils.fingersafe.BiometricPromptManager;
import com.lianzhihui.romeex.widget.keybord.SafetyKeyBoardDialog;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public class SplashActivity extends BaseNoRestartActivity implements SyncUserView {

    @BindView(R.id.iv_finger)
    ImageView ivFinger;
    private BiometricPromptManager mManager;
    SyncUserPresenter presenter;
    WalletInfo user;
    @BindView(R.id.logo_icon)
    ImageView logoIcon;
    @BindView(R.id.finger_hint)
    TextView fingerHint;
    @BindView(R.id.password_hint)
    TextView password_hint;
    Handler handler;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initView() {
        AppStatusManager.getInstance().setAppStatus(AppConstants.AppStatus.STATUS_NORMAL);
        handler = new Handler();
        presenter = new SyncUserPresenter(this, this);
        user = UserUtils.getCurrentUser();

        if (user == null) {
            List<WalletInfo> ws = UserUtils.getAllUserList();
            if (ws != null && ws.size() > 0) {
                //获取默认失败，如果数据库有用户资料
                user = ws.get(0);
                UserUtils.setCurrentUserAddress(user.getAddress());
            }
        }

        if (null != user && !TextUtils.isEmpty(user.getAddress())) {
            DataManager.setUserInfo(user);
            presenter.syncUser(UserUtils.getCurrentUserAddress());
        }
        ivFinger.setVisibility(View.GONE);
        password_hint.setVisibility(View.GONE);
        fingerHint.setVisibility(View.GONE);
        if (user == null) {
            //首次启动app
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent;
                    intent = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();

                }
            }, AppConstants.AppStatus.DELAY_MILLIS);
        } else {
            //获取当前用户是否设置了指纹。true已设置，false未设置
            boolean aBoolean = UserUtils.getCurrentFinger();
            if (aBoolean) {
                //已设置
                fingerVerify();
            } else {
                //未设置
                verifySafty();

            }
        }

    }


    @Override
    protected void initData() {
        String strLanguage = PreferenceUtils.getString(AppConstants.LANGUAGE_TYPE, "");
        String language = PreferenceUtils.getString(AppConstants.LANGUAGE_KEY, "");
        if (getApplicationContext() == null || getApplicationContext().getResources() != null || getApplicationContext().getResources().getConfiguration() == null) {
            return;
        }
        Locale locale = getApplicationContext().getResources().getConfiguration().locale;
        if (strLanguage.equals("follow")) {
            PreferenceUtils.applyString(AppConstants.LANGUAGE_KEY, locale.getLanguage());
            PreferenceUtils.applyString(AppConstants.LANGUAGE_TYPE, "follow");
        }
        if (!language.isEmpty() && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (strLanguage.equals("follow")) {
                LanguageUtil.changeAppLanguage(MyApplication.mContext, locale.getLanguage());
            } else {
                LanguageUtil.changeAppLanguage(MyApplication.mContext, language);
            }
        }
    }

    @Override
    public void onSync() {

    }

    @OnClick({R.id.iv_finger, R.id.password_hint})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_finger:
                //点击指纹登陆
                fingerVerify();
                break;
            case R.id.password_hint:
                //点击密码登陆
                verifySafty();
                break;
            default:
                break;

        }
    }

    /**
     * 指纹验证
     */
    private void fingerVerify() {
        mManager = BiometricPromptManager.from(SplashActivity.this, false);
        if (mManager.isBiometricPromptEnable()) {
            mManager.authenticate(new BiometricPromptManager.OnBiometricIdentifyCallback() {
                @Override
                public void onUsePassword() {
                }

                @Override
                public void onSucceeded() {
                    goneAllView();
                    //指纹验证成功
                    Intent intent;
                    intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }

                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onFailed() {
                    //指纹验证失败
//                    Toast.makeText(SplashActivity.this, "onFailed", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(int code, String reason) {
                    ivFinger.setVisibility(View.VISIBLE);
                    password_hint.setVisibility(View.VISIBLE);
                    fingerHint.setVisibility(View.VISIBLE);
                    switch (code) {
                        case 5:
                            //指纹操作已取消。
                            break;
                        case 7:
                            //尝试次数过多，请稍后重试。
                            break;
                        default:
                            break;
                    }
                    MyToast.showToast(reason);
                }

                @Override
                public void onCancel() {
                    //指纹验证取消
//                    Toast.makeText(SplashActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
                    ivFinger.setVisibility(View.VISIBLE);
                    password_hint.setVisibility(View.VISIBLE);
                    fingerHint.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    /**
     * 安全码验证
     */
    private void verifySafty() {
        //验证 安全码
        SafetyKeyBoardDialog loginConfirmDialog = new SafetyKeyBoardDialog(mActivity);
        loginConfirmDialog.setCallback(new CustomAllCallback() {
            @Override
            public void onCompare(Object o) {
                goneAllView();
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                loginConfirmDialog.dismiss();
                finish();
            }

            @Override
            public void onFailure(Object o) {
                password_hint.setVisibility(View.VISIBLE);
            }

            @Override
            public void dissmiss() {
                if (loginConfirmDialog.isInputStatus()) {
                    password_hint.setVisibility(View.GONE);
                } else {
                    password_hint.setVisibility(View.VISIBLE);
                }
            }
        });
        loginConfirmDialog.showToolBar(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //app状态改为正常
                Intent intent = new Intent(mActivity, WalletManagerActivity.class);
                intent.putExtra("isCheck", true);
                startActivity(intent);
                loginConfirmDialog.dismiss();
            }
        });
        if (!isFinishing()) {
            loginConfirmDialog.show();
        }
    }

    @Override
    public void onSyncFail(Object obj) {
        MyToast.showToast("同步失败");
//        DataManager.restartApplication();
    }


    private void goneAllView() {
        if (password_hint.getVisibility() == View.VISIBLE) {
            password_hint.setVisibility(View.GONE);
        }
        if (ivFinger.getVisibility() == View.VISIBLE) {
            ivFinger.setVisibility(View.GONE);
        }
        if (fingerHint.getVisibility() == View.VISIBLE) {
            fingerHint.setVisibility(View.GONE);
        }
    }

}